// pages/calendarList/calendarList.js
let app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        current: 0,
        toView: '',
        duration: 500,
        dateArr: [],
        week: ['日', '一', '二', '三', '四', '五', '六'],
        dateSpace: 3,
        info: [],
        contentArr: [],
        validityLowerBound: '1970-01-01',
        validityUpperBound: '2030-01-01',
        initDayObj: ''
    },
    navCalendar(){
      let data = this.data
      let activeDate = data.dateArr[data.current].filter(val => val.active)[0]
      let obj = {
        year: activeDate.year,
        month: activeDate.month,
        day: activeDate.date,
      }
      wx.navigateTo({
        url: '/pages/calendar/calendar?initDayObj=' + JSON.stringify(obj),
      })
    },
    navActivityDetail(e){
      const { item } = e.currentTarget.dataset
      let type 
      if (item.validityLowerBound){
        type = 'afterConsume'
      }
      else{
        type = 'deliverDirectly'
      }

      let day = this.data.dateArr[this.data.current].filter(val => val.active)[0]
      let dayObj = {
        year: day.year,
        month: day.month,
        day: day.date,
      }

      wx.navigateTo({
        url: `/pages/activityDetail/activityDetail?id=${item.id}&type=${type}&initDayObj=${JSON.stringify(dayObj)}`
      })
    },
    initDate(dateObj) {
        let dateObjDateString = dateObj.toDateString()
        var addDate = function (date, n) {
            date.setDate(date.getDate() + n);
            return date;
        };
        var setDate = (date) => {
            let arr = []
            //跨度
            date = addDate(date, - date.getDay() - Math.floor(this.data.dateSpace / 2) * 7);
            for (let i = 0; i < this.data.dateSpace * 7; i++) {
                let dateCalc
                if (i == 0) {
                    dateCalc = date
                }
                else {
                    dateCalc = addDate(date, 1)
                }

                let isCurrentDate = false
                let active = false

                if (dateObjDateString === dateCalc.toDateString()) {
                    // isCurrentDate = true
                    active = true
                    // if (type == 'init') {
                    //     active = true
                    // }
                }
                let year = dateCalc.getFullYear()
                let month = dateCalc.getMonth() + 1
                let day = dateCalc.getDate()
                let weekDay = dateCalc.getDay()
                let judgeObj = this.judge({
                    year,
                    month,
                    day,
                    weekDay
                }, this.data.info)

                if (judgeObj.length) {                           judgeObj[0].currentTime = `${month}月${day}日 周${this.data.week[dateCalc.getDay()]}`
                }
                arr.push({
                    year,
                    month,
                    date: day,
                    weekDay: dateCalc.getDay(),
                    hasActivity: !!judgeObj.length, 
                    active,
                    activityArr: JSON.parse(JSON.stringify(judgeObj))
                })
            }
            let result = []
            for (let i = 0; i < arr.length; i += 7) {
                result.push(arr.slice(i, i + 7));
            }
            return result
        };
        
        this.setData({
            dateArr: setDate(dateObj)
        })
    },
    judge(obj, info) {
      let activityArr = []
      info.afterConsume.forEach(val => {
        let valWeekDay = val.date == 7 ? 0 : val.date
        let valYear = val.validityLowerBound.split('-')[0]
        let valYear1 = val.validityUpperBound.split('-')[0]
        let valMonth = val.validityLowerBound.split('-')[1]
        let valMonth1 = val.validityUpperBound.split('-')[1]
        let valDay = val.validityLowerBound.split('-')[2]
        let valDay1 = val.validityUpperBound.split('-')[2]
        if (!+valMonth[0]) {
          valMonth = valMonth.substr(1)
          valMonth1 = valMonth1.substr(1)
        }
        if (!+valDay[0]) {
          valDay = valDay.substr(1)
          valDay1 = valDay1.substr(1)
        }
        if (+obj.year >= +valYear && +obj.year <= +valYear1) {
          if (+obj.month == +valMonth) {
            if (+obj.day >= +valDay && +obj.weekDay == valWeekDay) {
              activityArr.push(val)
            }
          }
          if (+obj.month > +valMonth && +obj.month < +valMonth1 && +obj.weekDay == valWeekDay) {

            activityArr.push(val)
          }
          if (+obj.month == +valMonth1) {
            if (+obj.day <= valDay1 && +obj.weekDay == valWeekDay) {
              activityArr.push(val)
            }
          }
        }
      })
      info.deliverDirectly.forEach(val => {
        let valYear = val.deliverDate.split('-')[0]
        let valMonth = val.deliverDate.split('-')[1]
        let valDay = val.deliverDate.split('-')[2]
        if (!+valMonth[0]) {
          valMonth = valMonth.substr(1)
        }
        if (!+valDay[0]) {
          valDay = valDay.substr(1)
        }
        if (+valYear == +obj.year && +valMonth == +obj.month && +valDay == +obj.day) {
          activityArr.push(val)
        }
      })
      return activityArr
    },
    /**
     * 生命周期函数--监听页面加载
     */
    initData(dayParam){
        app.globalData.post({
            url: '/activity/getList',
            data: {
                validityLowerBound: this.data.validityLowerBound,
                validityUpperBound: this.data.validityUpperBound
            },
            success: (data) => {
                this.setData({
                    info: data.data
                })
                let day = dayParam
                let selectDate = new Date(day.year, day.month - 1, day.day)
                let weekDay = selectDate.getDay() 
                this.setData({
                    current: Math.floor(this.data.dateSpace / 2)
                })
                this.initDate(selectDate, 'init')

                let contentArr = this.data.dateArr[this.data.current].reduce((a, b) => {
                    if (!Array.isArray(a)) {
                        return [a.activityArr, b.activityArr]
                    }
                    return [...a, b.activityArr]
                })
                this.setData({
                    contentArr
                })
                this.setData({
                    toView: `content${weekDay}`
                })
            }
        })
    },
    onLoad: function (options) {
        let day
        if(options.day){
          day = JSON.parse(options.day)
        }
        else{
          const date = new Date();
          const year = date.getFullYear();
          const month = date.getMonth() + 1
          const cday = date.getDate()
          day = {
            year,
            month,
            day: cday
          }
        }
        // console.log(options)
        // this.setData({
        //     info: JSON.parse(options.info)
        // })
        this.setData({
            initDayObj: day
        })
    },
    activeDate(e) {
        let swiperItemDateIndex = e.currentTarget.dataset.swiperitemdateindex
        let dayIndex = e.currentTarget.dataset.dayindex

        this.activeFun(swiperItemDateIndex, dayIndex)
        
    },
    activeFun(swiperItemDateIndex, dayIndex) {
        for (let i = 0; i < this.data.dateArr.length; i++) {
            for (let j = 0; j < this.data.dateArr[i].length; j++) {
                this.data.dateArr[i][j].active = false
            }
        }
        this.data.dateArr[swiperItemDateIndex][dayIndex].active = true
        this.setData({
            dateArr: this.data.dateArr,
            toView: `content${dayIndex}`
        })
    },
    finish(e) {
        let date, obj
        let space = this.data.dateSpace
        let current = e.detail.current
        if (+current === Math.floor(space / 2)) {
            return
        }
        this.setData({
            duration: 0
        })
        if (+current < Math.floor(space / 2)) {
            obj = this.data.dateArr[current][0]
        }
        else if (+current > Math.floor(space / 2)) {
            obj = this.data.dateArr[current][0]
        }
        date = new Date(obj.year, obj.month - 1, obj.date)
        this.initDate(date)

        wx.setNavigationBarTitle({
          title: `${obj.year}-${obj.month}`,
        })

        this.setData({
            current: Math.floor(space / 2)
        })

        let contentArr = this.data.dateArr[this.data.current].reduce((a, b) => {
            if (!Array.isArray(a)) {
                return [a.activityArr, b.activityArr]
            }
            return [...a, b.activityArr]
        })
        this.setData({
            contentArr
        })
    
        this.activeFun(Math.floor(space / 2), 0)

        this.setData({
            duration: 500
        })

    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
      wx.setNavigationBarTitle({
        title: `${this.data.initDayObj.year}-${this.data.initDayObj.month}`,
      })
        this.initData(this.data.initDayObj)
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})